package com.wendu.oa.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wendu.oa.common.Constants;
import com.wendu.oa.common.Result;
import com.wendu.oa.common.TokenUtils;
import com.wendu.oa.exception.BusinessException;
import com.wendu.oa.exception.SysException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class WdHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String path = request.getServletPath();//获取请求路径，例如：/security/login
        /**
         * 1. /security/login 放行
         */
        if("/security/login".equals(path)){
            return true;
        }

        // 2. 获得和验证token
        String token = request.getHeader(Constants.HEADER_TOKEN);
        try {
            TokenUtils.verify(token);
            return true;//true：放行通过，false拦截不通过
        } catch (BusinessException e) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();

            Result res = Result.err(Result.CODE_ERR_UNLONINED, e.getMessage());

            //json生成工具
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(res);
            out.print(jsonStr);

            out.flush();
            out.close();
            return false;
        } catch (SysException e) {
            log.error(e.getMessage(), e);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();

            Result res = Result.err(Result.CODE_ERR_UNLONINED, e.getMessage());

            //json生成工具
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(res);
            out.print(jsonStr);

            out.flush();
            out.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();

            Result res = Result.err(Result.CODE_ERR_UNLONINED, e.getMessage());

            //json生成工具
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(res);
            out.print(jsonStr);

            out.flush();
            out.close();
        }

        return false;


    }
}
